package com.smsc.headend.task.engine.handler.impl;

import cn.hutool.core.date.SystemClock;
import cn.hutool.core.map.MapUtil;
import com.smsc.headend.common.enums.PaymentSwithPreToPostOptGroupEnum;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.report.entity.LogModeSwitchHisSub;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.task.enums.SubTaskStatus;
import com.smsc.headend.module.task.enums.TaskType;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;


/**
 * @author liangli
 * @date 2020/9/25
 */
@Slf4j
public class ActionSuccessHandler implements TaskHandler {
    @Autowired
    TaskDAO taskDAO;

    @Autowired
    FeignAssetManagementService assetManagementService;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData cosemData, String actionResult) throws UDISTaskHandlerException {
        log.info("{} action result {}", atomicTask.getAtomicTaskNo(), actionResult);
        if (task.getIsODR()) {
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "result", 1, 600l, Boolean.TRUE);
        }
        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        if (task.getTaskType().equals(TaskType.SwitchMeterPayment.toString())) {
            Map<String, Object> parameterMap = getParameterMap(task, atomicTask);
            Long taskId = MapUtil.getLong(parameterMap, "taskId");
            assetManagementService.updateStepStatus(taskId, task.getMeterId(), LogModeSwitchHisSub.Step.SwitchMeterPayment,
                    SubTaskStatus.Failed.getCode(), null, SystemClock.now() / 1000, String.format("handle %s fail, %s", OperationName.forId(atomicTask.getOperationId()).getName(), message));
        }
        if (task.getTaskType().equals(TaskType.SwitchMeterPaymentPreToPost.toString())) {
            Map<String, Object> parameterMap = getParameterMap(task, atomicTask);
            Long taskId = MapUtil.getLong(parameterMap, "taskId");
            assetManagementService.updateStepStatusToPost(taskId,task.getTaskNo(), task.getMeterId(), PaymentSwithPreToPostOptGroupEnum.SWITCH_PAYMENT_FROM_PRE_TO_POST.getOperationGroup().longValue(),
                    SubTaskStatus.Failed.getCode(), null, SystemClock.now() / 1000, String.format("handle %s fail, %s", OperationName.forId(atomicTask.getOperationId()).getName(), message), false);
        }
        return -1;
    }
}
